import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { CommentInfo } from './comment';


@Injectable()
export class CommentDataProvider {

  private readonly baseUrl: string = 'https://api.bmob.cn/1';
  private readonly httpHeaders : HttpHeaders = new HttpHeaders(
    {
      'X-Bmob-Application-Id':'748054e798358354bf419b92c0dd9638',
      'X-Bmob-REST-API-Key':'452b75414d0a4920470d5ff482cb451d',
      'Content-Type':'application/json'
    }
  );

  constructor(public http: HttpClient) {
   
  }

   /**
   * 按新闻objectId获取相关点评
   * @param objectId 
   */
  getCommentByNewsId(objectId:string):Observable<any[]>{
    let whereStr = `{"newsId":{"__type":"Pointer","className":"news","objectId":"${objectId}"}}`;
    let _params = new HttpParams()
      .set('where', whereStr)
      .set('include', 'newsId,userId')
      .set('order', '-updatedAt');
    return this.http.get<any[]>(`${this.baseUrl}/classes/comments`, { headers: this.httpHeaders, params: _params }).map(val => val["results"]);
  }

  /**
   * 新增点评
   * @param commentInfo 
   */
  addComment(commentInfo: CommentInfo): Observable<CommentInfo> {
    let _commentInfo = {
      content: commentInfo.content,
      userId: {
        __type: "Pointer",
        className: "_User",
        objectId: commentInfo.userId
      },
      newsId: {
        __type: "Pointer",
        className: "news",
        objectId: commentInfo.newsId
      }
    }
    return this.http.post<CommentInfo>(`${this.baseUrl}/classes/comments`, _commentInfo, { headers: this.httpHeaders });
  }

}
